package org.s170.servlet.WebServlet;

import org.s170.dao.UserDao;
import org.s170.entity.User;
import org.s170.servlet.BaseServlet;
import org.s170.utils.JwtUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/user/login")
public class UserLoginServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        // DAO对象 -- 省略
        UserDao userDao = new UserDao();
        User user = userDao.findUser(email,password);

        System.out.println(email+"="+password);

        // 验证用户是否合法：非空帐号和密码登录成功
        if (user != null) {
            // 定义一个Map对象，用于封装相关的令牌
            Map<String, Object> map = new HashMap<>();
            // 封装数据 -- 客户端浏览器只保留帐号名（用户ID）即可
            map.put("username", user.getUsername());

            // 创建Token,设置有效时间为30分钟
            String token = JwtUtil.createToken(map, 30 * 60 * 1000);
            // 响应客户端
            print(resp, successJson(token));
            return;
        }
        print(resp, errorJson(401, "错误的帐号或密码"));
    }

}
